<template>
  <div class="flex h-full">
    <div class=""><Ueditor ref="ueditorRef" /></div>
    <div class="flex flex-col justify-between h-full p-2 overflow-hidden w-247px">
      <div class="p-1 mb-2 font-bold border border-gray-400 border-solid">视图设计器</div>
      <div class="mb-2">
        <Input
          class="h-30px"
          placeholder="搜素"
          @change="handleSearchData"
          style="border: 1px solid gray"
        />
      </div>
      <div class="flex-auto pr-1 mb-2 overflow-y-scroll">
        <ul>
          <li
            class="p-1 mb-1 overflow-hidden rounded-sm cursor-pointer"
            style="border-bottom: 1px solid #ccc"
            v-for="(item, index) in formGetFields"
            :key="index"
            @click="handleClick(item)"
          >
            {{ item.label }}</li
          >
        </ul>
      </div>
      <div class="flex justify-center gap-2">
        <a-button type="primary" @click="handleOk" :loading="loading">确定</a-button>
        <a-button @click="handleCancel">关闭</a-button>
      </div>
    </div>
  </div>
</template>
<script lang="ts" setup>
  import { ref, onMounted, nextTick } from 'vue';
  import Ueditor from '/@/components/Ueditor/index.vue';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { Input } from 'ant-design-vue';
  import { useRouter } from 'vue-router';
  import { useDebounceFn } from '@vueuse/core';
  import { getFormGetFields } from '/@/api/flowManage/flowManage';
  import { getFormViewGetViewById, getFormViewUpdate } from '/@/api/formDesign/formDesign';
  const { currentRoute } = useRouter();
  const state = ref<Recordable>({
    formCode: '',
  });
  const loading = ref(false);
  const ueditorRef = ref<any>(null);
  const { createMessage } = useMessage();

  //写入
  const handleWrite = (content) => {
    const { setContent, hasContent } = ueditorRef.value;
    setTimeout(() => {
      if (content) {
        setContent(content);
      }
      // setContent('563');
    }, 200);
  };
  //聚焦
  const handleFocus = () => {
    const { setFocus } = ueditorRef.value;
    setFocus();
  };
  //获取
  const handleGetConment = () => {
    const { getAllHtml, getContent } = ueditorRef.value;
    return getContent();
  };
  //插入
  const handleInsertHtml = (value) => {
    const { insertHtml } = ueditorRef.value;
    insertHtml(value);
  };

  const formGetFields = ref<Recordable[]>([]);
  const oldFormGetFields = ref<Recordable[]>([]);
  const getFormGetFieldsData = async () => {
    let params = {
      formCode: state.value.formCode,
    };
    if (!params.formCode) return;
    try {
      const data = (await getFormGetFields(params)) || [];
      formGetFields.value = data.map((item) => {
        delete item.options;
        return {
          ...item,
          label: item.title,
          value: item.name,
        };
      });
      oldFormGetFields.value = [...formGetFields.value];
    } catch (err) {
      console.log('getFormGetFieldsData', err);
    }
  };

  function handleClick({ label, value }) {
    handleInsertHtml(`<input value='${label}' title='${label}' name='${value}' />`);
  }

  const getFormViewGetViewByIdData = async () => {
    const { query } = currentRoute.value as any;
    state.value = await getFormViewGetViewById({ id: query.id });
    handleWrite(state.value.content);
    await getFormGetFieldsData();
  };

  const handleSearch = (e) => {
    const data = oldFormGetFields.value.filter((item) => item.label.includes(e.target.value));
    formGetFields.value = data;
  };
  // 防抖，延迟500ms执行
  const handleSearchData = useDebounceFn(handleSearch, 500);

  const fetch = async () => {
    await nextTick();
    getFormViewGetViewByIdData();
  };
  onMounted(fetch);

  const handleOk = async () => {
    try {
      const content = await handleGetConment();
      const params = {
        ...state.value,
        content,
      };
      loading.value = true;
      await getFormViewUpdate(params);
      createMessage.success('操作成功');
      // handleCancel();
    } catch (error) {
      console.error(error);
    } finally {
      loading.value = false;
    }
  };
  const handleCancel = () => {
    window.close();
  };
</script>

<style scoped>
  #editor {
    height: calc(100vh - 100px);
    width: calc(100% - 200px);
  }
</style>
